package jmine.tec.web.wicket.validator;

import java.io.Serializable;

import jmine.tec.web.wicket.spring.SpringBeanReference;

import org.apache.wicket.validation.IValidatable;
import org.apache.wicket.validation.IValidator;
import org.apache.wicket.validation.ValidationError;

import bancosys.tec.persist.Persistable;
import bancosys.tec.persist.dao.BaseDAO;
import bancosys.tec.persist.dao.BaseDAOFactory;
import bancosys.tec.persist.dao.BeanNotFoundException;

/**
 * @author finx
 * @created Jul 21, 2010
 * @param <T> Tipo da entidade a ser validada.
 */
public class NaturalKeyIValidator<T extends Persistable> implements IValidator<T>, Serializable {

    private Class<? extends T> clazz;

    /**
     * Construtor.
     * 
     * @param clazz a classe do persistível a ser validado.
     */
    public NaturalKeyIValidator(Class<? extends T> clazz) {
        this.clazz = clazz;
    }

    /**
     * {@inheritDoc}
     */
    public void validate(IValidatable<T> validatable) {
        BaseDAO<T> dao = SpringBeanReference.forType(BaseDAOFactory.class).get().getGenericDAO(this.clazz);
        T value = validatable.getValue();
        if (clazz.isInstance(value)) {
            if (value.getPk() == null) {
                validationError(validatable, value);
            }
        } else {
            try {
                dao.findByNaturalKey((Serializable) value);
            } catch (BeanNotFoundException e) {
                validationError(validatable, value);
            }
        }
    }

    /**
     * Sets an error message on the given {@link IValidatable}
     * 
     * @param validatable the {@link IValidatable}
     * @param value the value
     */
    private void validationError(IValidatable<T> validatable, T value) {
        ValidationError error = new ValidationError();
        // TODO (finx) : internacionalizar
        error.setMessage(this.clazz.getSimpleName() + " '" + value + "' não encontrado.");
        validatable.error(error);
    }
}
